package org.ultrapower.checkuser.web;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.ultrapower.checkuser.Constants;
import org.ultrapower.checkuser.HttpCode;
import org.ultrapower.checkuser.core.util.DateUtil;
import org.ultrapower.checkuser.core.util.FileUtil;
import org.ultrapower.checkuser.service.CheckService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.List;

/**
 * Created by zhaopan on 2017/7/6.<br>
 *
 * @Description:
 */
@WebServlet("/BatchAuth")
public class BatchAuthServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        response.setContentType("application/json");
        //设置响应头允许ajax跨域访问,星号表示所有的异域请求都可以接受
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");
        JSONObject jsonObject = new JSONObject();
        Writer out = null;
        try {
            out = response.getWriter();
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //获取文件需要上传到的路径， 得到项目的绝对路径
            String outPath = Constants.OUTPATH;
            //如果没以下两行设置的话，上传大的 文件 会占用 很多内存，
            //设置暂时存放的 存储室 , 这个存储室，可以和 最终存储文件 的目录不同
            /**
             * 原理 它是先存到 暂时存储室，然后在真正写到 对应目录的硬盘上，
             * 按理来说 当上传一个文件时，其实是上传了两份，第一个是以 .tem 格式的
             * 然后再将其真正写到 对应目录的硬盘上
             */
            factory.setRepository(new File(outPath));
            //设置 缓存的大小，当上传文件的容量超过该缓存时，直接放到 暂时存储室
            factory.setSizeThreshold(1024 * 1024);
            //高水平的API文件上传处理
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding(request.getCharacterEncoding());
            List<FileItem> list = upload.parseRequest(request);
            for (int i = 0; i < list.size(); i++) {
                FileItem item = list.get(i);
                if (item.getName().endsWith(".xls") || item.getName().endsWith(".xlsx")) {
                    //获取路径名
                    String value = item.getName();
                    //索引到最后一个反斜杠
                    int start = value.lastIndexOf("\\");
                    //截取 上传文件的 字符串名字，加1是 去掉反斜杠，
                    String fileFullName = value.substring(start + 1);
                    String[] name = fileFullName.split("\\.");
                    String filename = name[0];
                    String type = name[1];
                    //保存文件
                    String dateString = DateUtil.getDateTime("yyyyMMddHHmmssSSS");
                    FileUtil.saveFile(new File(outPath, filename + "_" + dateString + "." + type), item.getInputStream());
                    //批量检验
                    //XxlsFindByHbaseHelper howto = new XxlsFindByHbaseHelper();

                    String fileName = CheckService.BatchCkeckoutUserByFile(new File(outPath, filename + "_" + dateString + "." + type));

                    jsonObject.put("httCode", HttpCode.OK.value());//报错
                    jsonObject.put("result", "0");
                    jsonObject.put("data", fileName);
                    out.write(jsonObject.toString());
                    out.flush();
                } else {
                    jsonObject.put("httCode", HttpCode.REQUEST_TIMEOUT.value());//408文件格式不符合要求
                    jsonObject.put("result", "-1");
                    out.write(jsonObject.toString());
                    out.flush();
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (out == null) out = response.getWriter();
            jsonObject.put("httCode", HttpCode.INTERNAL_SERVER_ERROR.value());//报错
            jsonObject.put("result", "-1");
            out.write(jsonObject.toString());
            out.flush();
        }
    }
}